package com.company.project.configurer;

import com.company.project.core.ProjectConstant;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description TODO
 * <p>
 * @author： li
 * @Date 2021/3/29 15:24
 */
@Aspect
@Component
public class LogConfig {
	/**
	 * 保存信息到当前线程
	 */
	public static final ThreadLocal<Map<String, String>> INFO = new ThreadLocal<>();

	Logger log = LoggerFactory.getLogger(LogConfig.class);

	//需根据项目设置路径自己调整
	@Pointcut(ProjectConstant.LOG_ACCECP)
	public void webLog() { }

	/**
	 * 日志记录请求内容
	 * @param joinPoint
	 * @throws Throwable
	 * 2020年2月6日 上午10:40:16  
	 */
	@Before("webLog()")
	public void doBefore(JoinPoint joinPoint) throws Throwable {
		// 接收到请求，记录请求内容
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();

		Signature signature = joinPoint.getSignature();
		//MethodSignature methodSignature = (MethodSignature) signature;
		//String[] names = methodSignature.getParameterNames();
		//Object[]  args = joinPoint.getArgs();
		String method = signature.getDeclaringTypeName() + "." + signature.getName();
		String args = Arrays.toString(joinPoint.getArgs());

		Map<String, String> map = new HashMap<String, String>();
		map.put("method", method);
		map.put("args", args);
		INFO.set(map);
		// 记录下请求内容
		log.info("URL : " + request.getRequestURL().toString());
		log.info("HTTP_METHOD : " + request.getMethod());
		log.info("IP : " + request.getRemoteAddr());
		log.info("CLASS_METHOD : " + method);
		log.info("ARGS : " + args);
	}


	/**
	 * 日志记录返回结果
	 * @param ret
	 * @throws Throwable   
	 */
	@AfterReturning(returning = "ret", pointcut = "webLog()")
	public void doAfterReturning(Object ret) throws Throwable {
		INFO.remove();
		// 处理完请求，返回内容
		if (null == ret) {
			log.info("返回结果 : null");
		} else {
			log.info("返回结果 : " + ret.toString());
		}
	}
}
